<template>
	<div class="hd Confirm">
		<div class="hd mt10">
			<img src="../../assets/banner03.png">
		</div>

		<div class="hd mt10">
			<sider-menu :activeNumber="2"></sider-menu>
			<div class="right-content">
				<position style="padding:12px;width:auto;">
					<router-link to="/personal">个人中心</router-link>
					&gt;
					<span class="last">我的家庭</span>
				</position>

				<div class="clearfix main my-family">
          <div class="tips-warning">已添加 {{familys.length}} 人，还可添加 {{6-familys.length}} 人</div>
					<div class="my-family-item" v-for="(f, i) in familys" :key="f.mpiId">
              <div class="title">{{f.personName}}<small class="t3">（{{FAMILY_RALATION[f.relation]}}）</small></div>
              <div class="edit" @click="editFamily(f)" v-show ="i > 0">
                <i class="iconfont icon-edit"></i> 编辑
              </div>
             
              <div class="del" @click="delFamily(f)" v-show="i > 0">
                <i class="iconfont icon-detele"></i> 删除
              </div>
              <ul class="lists">
                <li><span class="t3">性别：</span> {{SEX[f.sex]}}</li>
                <li><span class="t3">年龄：</span> {{new Date().getFullYear() - (f.dob && f.dob.substr(0, 4))}}</li>
                <li><span class="t3">电话：</span> {{f.phoneNo}}</li>
                <li><span class="t3">证件类型：</span> {{CARD_TYPE[f.certificate.certificateType]}}</li>
                <li><span class="t3">证件号：</span> {{f.certificate.certificateNo}}</li>
              </ul>
          </div>

          <div class="my-family-item has-addicon" @click="editFamily" v-show="familys.length < 6">
             <i class="iconfont icon-jia1" title="新增家人"></i>
          </div>

				</div>
				</div>
		</div>

     <el-dialog :visible.sync="dialogShow" custom-class=" dialog-common">
      <div class="dialog-title" slot="title">
        {{dialogTitle}}
      </div>
      <div class="dialog-content">
       <el-form :model="ruleForm" :rules="rules" ref="ruleForm"  label-width="100px">
          <el-form-item label="关系" prop="relation" required>
            <el-select v-model="ruleForm.relation" required :disabled="disabled.relation">
              <el-option
              v-for="(value, key) in FAMILY_RALATION"
              :key="key"
              :label="value"
              :value="key">
             </el-option>
          </el-select>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName" required>
            <el-input v-model="ruleForm.realName" placeholder="请输入真实姓名" :maxlength="6" :disabled="disabled.realName"></el-input>
          </el-form-item>
         
          <el-form-item label="证件类型" prop="cardType" required>
            <el-select v-model="ruleForm.cardType" required :disabled="disabled.cardType">
              <el-option
              v-for="(value, key) in CARD_TYPE"
              :key="key"
              :label="value"
              :value="key">
             </el-option>
          </el-select>
          </el-form-item>
          <el-form-item label="证件号码" prop="cardNo" required>
            <el-input v-model="ruleForm.cardNo" placeholder="请输入证件号码" :maxlength="18" :disabled="disabled.cardNo"></el-input>
          </el-form-item>
           <el-form-item label="性别" prop="sex" required>
              <el-radio class="radio" v-model="sex" label="1" :disabled="disabled.sex">男</el-radio>
              <el-radio class="radio" v-model="sex" label="2" :disabled="disabled.sex">女</el-radio>
          </el-form-item>
            <el-form-item label="出生年月" prop="bornDate" required>
             <el-date-picker
              v-model="bornDate"
              type="date"
              placeholder="请选择出生年月"
              style="width:100%;" :disabled="disabled.bornDate">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber" required="">
            <el-input v-model="ruleForm.phoneNumber" placeholder="请输入手机号" type="text" :minlength="11" :maxlength="11" :disabled="disabled.phoneNumber"></el-input>
          </el-form-item>
       </el-form>
      </div>
      <div class="center" slot="footer">
        <a href="javascript:;" class="common-main-button"  @click="confirmSubmit('ruleForm')">提交</a>
						<a href="javascript:;"  class="common-sub-button" @click="dialogShow=false">取消</a>
      </div>
    </el-dialog>

	</div>
</template>

<script>
import Position from '../../components/Position'
import SiderMenu from '../../components/SiderMenu'
import {commonAjax, PLATFORM_PREFIX, SEX, CARD_TYPE, FAMILY_RALATION} from '../../api/api'
import {getBirthdayFromIdCard, testCardNumber, getSexFromIdCard, testPhone} from '../../common/js/util'

export default {
	data () {
		return {
      dialogShow: false,
      dialogTitle: '提示',
      defaultRuleForm: {
        relation: '0',
        realName: '',
        sex: '1',
        cardType: '01',
        cardNo: '',
        phoneNumber: '',
        bornDate: ''
      },
      ruleForm: {
        relation: '0',
        realName: '',
        cardType: '01',
        cardNo: '',
        phoneNumber: '',
      },
      sex: '1',
      bornDate: '',
      defaultDisabled: {
        relation: false,
        realName: false,
        sex: false,
        cardType: false,
        cardNo: false,
        bornDate: false,
        phoneNumber: false
      },
      disabled: {
        relation: false,
        realName: false,
        sex: false,
        cardType: false,
        cardNo: false,
        bornDate: false,
        phoneNumber: false
      },
      rules: {
        realName: {required: true, message: '真实姓名不能为空'},
        cardNo: {required: true, message: '证件号码不能为空'},
        cardNo: {required: true, message: '手机号码不能为空'}
      },
      familys: [],
      SEX: SEX,
      CARD_TYPE: CARD_TYPE,
      FAMILY_RALATION: FAMILY_RALATION
		}
  },
  watch: {
    'ruleForm.cardNo': function (val) {
      if (this.ruleForm.cardType === '01') {
        this.bornDate = getBirthdayFromIdCard(val)
        this.sex = getSexFromIdCard(val)
      }
    }
  },
  methods: {
    editFamily (f, i) {
      this.dialogShow = true
      if (typeof f.phoneNo !== 'undefined') {
        // 修改成员 f default value is click event
        this.dialogTitle = '修改家庭成员'
        if (f.certificate && f.certificate.certificateType === '01') {
          // 证件为身份证 只能修改手机号
          this.disabled = {
            relation: true,
            realName: true,
            sex: true,
            cardType: true,
            cardNo: true,
            bornDate: true,
            phoneNumber: false
          }
        } else {
          // 证件为其他证件  能修改出生日期、性别、手机号
          this.disabled = {
            relation: true,
            realName: true,
            sex: true,
            cardType: true,
            cardNo: true,
            bornDate: true,
            phoneNumber: false
          }
        }
        this.ruleForm = {
          relation: f.relation,
          realName: f.personName,
          cardType: f.certificate.certificateType,
          cardNo: f.certificate.certificateNo,
          phoneNumber: f.phoneNo,
          mpiId: f.mpiId
        }
        this.sex = f.sex
        this.bornDate = f.dob
      } else {
        // 添加成员
        this.dialogTitle = '添加家庭成员'
        this.disabled = this.defaultDisabled
        this.ruleForm = this.defaultRuleForm
      }
    },
    delFamily (f) {
      this.$confirm('此操作将永久删除该成员, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        commonAjax([f.mpiId], `${PLATFORM_PREFIX}.familyService`, 'deleteFamilyMember').then(res => {
          if (res.data.code === 200) {
            this.$message({type: 'success', message: '删除成功'})
            setTimeout(() => location.reload(), 600)
          } else {
            this.$message({type: 'error', message: res.data.msg})
          }
        })
      }).catch((res) => {
        console.warn(res)
      })
    },
    getFamilys () {
      this.$store.commit('UPDATE_LOADING')
      commonAjax([true], `${PLATFORM_PREFIX}.familyService`, 'getFamilyMemberList').then(res => {
        this.$store.commit('UPDATE_LOADING')
        if (res.data.code === 200) {
          this.familys = res.data.body || []
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
        }
      }).catch(res => {
        this.$store.commit('UPDATE_LOADING')
        this.$message({
          message: '请求服务器失败',
          type: 'error'
        })
      })
    },
    confirmSubmit (form) {
      this.$refs[form].validate(valid => {
        if (!valid) {
          return false
        }
        // 只验证身份证格式
        if (!testCardNumber(this.ruleForm.cardNo) && this.ruleForm.cardType === '01') {
          this.$message({message: '身份证号码格式有误', type: 'error'})
          return
        }
        if (!testPhone(this.ruleForm.phoneNumber)) {
          this.$message({message: '手机号码格式有误', type: 'error'})
          return
        }
        commonAjax([{
          certificateNo: this.ruleForm.cardNo,
          certificateType: this.ruleForm.cardType,
          source: '01'
        }], `${PLATFORM_PREFIX}.familyService`, 'checkFamilyMember').then(res => {
          if (res.data.code === 200) {
            if (res.data.body) {
              this.ruleForm.mpiId = res.data.body.mpiId
            }
            this.$store.commit('UPDATE_LOADING')
            commonAjax([{
              personName: this.ruleForm.realName,
              sex: this.sex,
              phoneNo: this.ruleForm.phoneNumber || '',
              dob: this.bornDate,
              mpiId: this.ruleForm.mpiId || '',
              certificate: {
                certificateType: this.ruleForm.cardType,
                certificateNo: this.ruleForm.cardNo,
                source: '01' // 中国
              }
            }, this.ruleForm.relation], `${PLATFORM_PREFIX}.familyService`, 'saveFamilyMember').then(res => {
              this.$store.commit('UPDATE_LOADING')
              if (res.data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                setTimeout(() => location.reload(), 2000)
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                })
              }
            }).catch(res => {
              this.$store.commit('UPDATE_LOADING')
              this.$message({
                message: '请求服务器失败',
                type: 'error'
              })
            })
          } else {
            this.$message({message: res.data.msg, type: 'error'})
          }
        })
      })
    }
  },
	mounted () {
    this.getFamilys()
	},
	components: {Position, SiderMenu}
};
</script>
<style lang="less">
@import '../../common/css/vars.less';
.my-family {
  overflow: hidden;
  margin-right: -20px;
  .tips-warning {
      line-height: 2;
      font-size: 16px;
      text-align: center;
      background: #FFD38A;
      color: @color-price;
      margin-right: 20px;
      margin-bottom: 10px;
    }
  .my-family-item {
    position: relative;
    width: 266px;
    margin: 10px 10px 10px 0;
    float: left;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .1);
    background: #fff;
    border-radius: 2px;
    height: 260px;
    &:hover {
      box-shadow: 0 0 5px rgba(0, 0, 0, .4);
    }
    &.has-addicon {
      padding-top: 52px;
      text-align: center;
    }
    .title {
      font-size: 18px;
      margin: 20px 16px 0;
      border-bottom: 1px solid #eee;
      padding-bottom: 20px;
    }
    .edit, .del{
      position: absolute;
      right: 16px;
      top: 6px;
      color: @color-primary;
      cursor: pointer;
      opacity: 0;
      transition: all .5s;
      transform: translate3d(0,-100%,0);
    }
   
     .del{
      right: 16px;
      top: 34px;
      color: @color-price;
    }
    
     &:hover {
      .edit, .del {
        opacity: 1;
        transform: translate3d(0,0,0);
      }
    }
    .lists {
      padding: 16px;
      li {
        line-height: 2;
      }
    }
    .icon-jia1 {
      font-size: 6em;
      color: #ddd;
      cursor: pointer;
    }
  }
}
.dialog-common {
  .dialog-content {
    width: 400px;
    margin:0 auto;
  }
}
</style>
